package com.vitabuybuy.tv.ui.mine.talent.usercenter

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.luck.picture.lib.PictureSelector
import com.library.common.BuildConfig
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityTalentEditInfoBinding
import com.vitabuybuy.tv.dialog.OptionsDialog
import com.vitabuybuy.tv.dto.CaseBean
import com.vitabuybuy.tv.dto.FieldLabelDto
import com.vitabuybuy.tv.dto.RegionDto
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.base.appContext
import com.library.common.ext.logE
import com.library.common.ext.mmkv
import com.library.common.ext.setOnclickNoRepeat
import com.library.common.net.NetUrl
import com.library.common.toast.XToast
import com.library.common.util.AppManager
import com.library.common.util.JsonUtil
import com.library.common.util.MMKVContancts
import com.library.common.util.PictureUtils
import com.vitabuybuy.tv.ui.MainActivity
import com.vitabuybuy.tv.ui.mine.talent.FieldLabelActivity
import com.vitabuybuy.tv.ui.mine.talent.usercenter.viewmodel.UserCenterViewModel
import com.vitabuybuy.tv.ui.tencent.liveroom.IMLVBLiveRoomListener
import com.vitabuybuy.tv.ui.tencent.liveroom.MLVBLiveRoom
import com.vitabuybuy.tv.ui.tencent.liveroom.roomutil.commondef.LoginInfo
import com.vitabuybuy.tv.widget.selector.BottomDialog
import com.vitabuybuy.tv.widget.selector.SelectedListener
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_talent_edit_info.*

class TalentEditInfoActivity :
    BaseActivity<UserCenterViewModel, ActivityTalentEditInfoBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_talent_edit_info

    private val genderDialog by lazy { OptionsDialog(mContext) }
    private val picDialog by lazy { OptionsDialog(mContext) }
    private var areaDialog: BottomDialog? = null
    private var REQUEST_CODE_CAMMER = 10002
    private var regionId = -1
    private val fieldLabellist = ArrayList<FieldLabelDto>()

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.my_business_card))
        mBinding.mViewModel = viewModel
        mTvRight.apply {
            text = getString(R.string.confirm)
            visibility = View.VISIBLE
        }
    }

    override fun observeData() {
        viewModel.isFirstLoading.set(true)
        viewModel.getTalentUserInfo()
        viewModel.applyTalentUserInfo.observe(this, Observer {
            it.regionList?.run {
                if (this.isNotEmpty())
                    regionId = this[0].id
            }
            it.labelList?.run {
                fieldLabellist.addAll(this)
                var labels = ""
                for (label in fieldLabellist) {
                    labels = "$labels${label.name}、"
                }
                tvFieldLable.text = if (labels.isNotEmpty()) {
                    labels.substring(0, labels.length - 1)
                } else labels
            }
        })
    }

    override fun eventHandling() {
        setOnclickNoRepeat(
            rlAvatar, spnChoose,
            tvBirthday, rlFieldLabel
        ){v->
            when (v) {
                rlAvatar -> {
                    AndPermission.with(this)
                        .runtime()
                        .permission(Permission.Group.CAMERA, Permission.Group.STORAGE)
                        .onDenied {
                            if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                                // 这些权限被用户总是拒绝。
                                XToast.normal(getString(R.string.request_necessary_permissions))
                            }
                        }
                        .onGranted {
                            picDialog.show()
                        }.start()
                }
                spnChoose -> {
                    genderDialog.setBtnStr(getString(R.string.male), getString(R.string.female))
                    genderDialog.show()
                }
                tvBirthday -> {
                    areaDialog = BottomDialog(this, 1)
                    viewModel.getRegionList(null)
                }
                rlFieldLabel -> {
                    FieldLabelActivity.openActivity(mContext, fieldLabellist)
                }
            }
        }
        genderDialog.onTwoClick = {
            spnChoose.text = getString(R.string.female)
        }
        genderDialog.onOneClick = {
            spnChoose.text = getString(R.string.male)
        }
        picDialog.onTwoClick = {
            PictureUtils.openAluamOneRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        picDialog.onOneClick = {
            PictureUtils.openCameraRectangle(mContext, REQUEST_CODE_CAMMER)
        }
        mTvRight.setOnClickListener {
            if (etNickName.text.isEmpty()) {
                XToast.normal(getString(R.string.name_tip_2))
                return@setOnClickListener
            }
            if (regionId == -1) {
                XToast.normal(getString(R.string.please_choose_coutry))
                return@setOnClickListener
            }
            if (etIdCard.text.isEmpty()) {
                XToast.normal(getString(R.string.id_card_number_tip))
                return@setOnClickListener
            }
            if (fieldLabellist.isEmpty()) {
                XToast.normal(getString(R.string.please_choose_field_label))
                return@setOnClickListener
            }
            val params = HashMap<String, Any>()
            viewModel.applyTalentUserInfo.value?.avatar?.run {
                params["avatar"] = this
            }
            params["realname"] = etNickName.text.toString()
            params["gender"] = spnChoose.text.toString()
            params["IDCardNumber"] = etIdCard.text.toString()
            params["region"] = mapOf(Pair("id", regionId))
            params["labelList"] = fieldLabellist
            if (etFacebookPage.text.isNotEmpty()) {
                params["facebookLink"] = etFacebookPage.text.toString()
            }
            if (etFacebookFans.text.isNotEmpty()) {
                params["facebookFansQuantity"] = etFacebookFans.text.toString()
            }
            if (etFacebookId.text.isNotEmpty()) {
                params["facebookId"] = etFacebookId.text.toString()
            }
            if (etFacebookPromotionPrice.text.isNotEmpty()) {
                params["facebookPrice"] = etFacebookPromotionPrice.text.toString()
            }
            if (etInstagramPage.text.isNotEmpty()) {
                params["instagramLink"] = etInstagramPage.text.toString()
            }
            if (etInstagramFans.text.isNotEmpty()) {
                params["instagramFansQuantity"] = etInstagramFans.text.toString()
            }
            if (etInstagramId.text.isNotEmpty()) {
                params["instagramId"] = etInstagramId.text.toString()
            }
            if (etInstagramPromotionPrice.text.isNotEmpty()) {
                params["instagramPrice"] = etInstagramPromotionPrice.text.toString()
            }
            if (etTwitterPage.text.isNotEmpty()) {
                params["twitterLink"] = etTwitterPage.text.toString()
            }
            if (etTwitterFans.text.isNotEmpty()) {
                params["twitterFansQuantity"] = etTwitterFans.text.toString()
            }
            if (etTwitterId.text.isNotEmpty()) {
                params["twitterId"] = etTwitterId.text.toString()
            }
            if (etTwitterPromotionPrice.text.isNotEmpty()) {
                params["twitterPrice"] = etTwitterPromotionPrice.text.toString()
            }
            val executorMap = HashMap<String, Any>()
            executorMap["executor"] = params
            JsonUtil.toJson(executorMap).logE()
            viewModel.updateTalent(executorMap)
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0 -> {
                viewModel.getTalentUserInfo()
            }
            1 -> {
                areaDialog?.run {
                    this.setDataRegion(msg.obj as MutableList<RegionDto>)
                    this.setOnAddressSelectedListener(object : SelectedListener {
                        override fun onAddressSelected(selectAbles: ArrayList<RegionDto>?) {
                        }

                        override fun onClickOnEach(selectAble: RegionDto?) {
                            selectAble?.run {
                                regionId = this.id
                                mBinding.tvBirthday.text = this.name
                            }
                        }
                    })
                    if (this.isShowing) return
                    this.show()
                }
            }
            2 -> {
                viewModel.applyTalentUserInfo.value?.avatar =
                    NetUrl.FILE_PROFILE.plus(msg.obj as String)
            }
            3 -> {
//                MLVBLiveRoom.sharedInstance(appContext).logout{
                val loginInfo = LoginInfo().apply {
                    sdkAppID = com.vitabuybuy.tv.BuildConfig.LIVEAPPID.toLong()
                    userID = mmkv.decodeInt(MMKVContancts.USER_ID, 0).toString()
                    userSig = mmkv.decodeString(MMKVContancts.USER_SIGN, "")
                    userName = mmkv.decodeString(MMKVContancts.USER_NICKNAME, "")
                    userAvatar = mmkv.decodeString(MMKVContancts.USER_AVATAR, "")
                }
                MLVBLiveRoom.sharedInstance(appContext)
                    .login(loginInfo, object : IMLVBLiveRoomListener.LoginCallback {
                        override fun onSuccess() {
                            AppManager.get().finishActivitiesWithoutTarget(MainActivity::class.java)
                            XToast.success(getString(R.string.update_success_wait_auth))
                        }

                        override fun onError(errCode: Int, errInfo: String?) {
                            errInfo?.run {
                                errCode.logE("JIA--errCode--")
                                this.logE("JIA--errInfo--")
                                XToast.error("直播登录失败，请联系管理员")
                            }
                        }
                    })
//                }
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        when (requestCode) {
            REQUEST_CODE_CAMMER -> {
                val path = PictureSelector.obtainMultipleResult(data)[0].cutPath
                viewModel.uploadImage(path)
            }
            10001 -> {
                fieldLabellist.clear()
                fieldLabellist.addAll(data?.getSerializableExtra("labelList") as ArrayList<FieldLabelDto>)
                var labels = ""
                for (label in fieldLabellist) {
                    labels = "$labels${label.name}、"
                }
                tvFieldLable.text = if (labels.isNotEmpty()) {
                    labels.substring(0, labels.length - 1)
                } else labels
            }
        }
    }


    companion object {
        fun openActivity(mContext: BaseActivity<*, *>) {
            mContext.startActivity(
                null,
                TalentEditInfoActivity::class.java
            )
        }
    }
}
